#include "user.h"
#include "socket.h"

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

extern char g_ip[];

int UserNum = 0;
struct UserTable UT;

struct user self;

int User_Init(int port, const char* name)
{
    self.name = name;
    self.port = port;
}


struct user* User_QueryByPort(int port)
{
    if(port == self.port) return &self;

    const struct user* p = NULL;
    TGAP_LIST_TRAVERSE(&UT, p, field){
        if(p->port == port) return p;
    }
    return NULL;
}

struct user* User_Add(int port, const char* name)
{
    struct user* NewUser = (struct user*)malloc(sizeof(struct user));
    NewUser->name = (char*)malloc(sizeof(char) * USER_NAME_SIZE);
    strcpy(NewUser->name, name);
    NewUser->port = port;

    TGAP_LIST_INSERT_HEAD(&UT, NewUser, field);
    return NewUser;
}

struct user* User_RemoveByPort(int port)
{
    if(port == self.port) return NULL;
    struct user* u = User_QueryByPort(port);
    if(u != NULL)
        TGAP_LIST_REMOVE(&UT, u, field);
    free(u);
    return u;
}


void PrintUserTable()
{
    printf("----------Online User----------\n");
    printf("self:%s uid:%d\n\n", self.name, self.port);

    struct user* u = NULL;
    TGAP_LIST_TRAVERSE(&UT, u, field){
        printf("user:%s uid:%d\n", u->name, u->port);
    }
    printf("------------------------------\n");
}

